#include "VTKModelStudio.h"

// VTK 相关头文件
#include <vtkNamedColors.h>
#include <vtkTriangleFilter.h>
#include <vtkMassProperties.h>
#include <vtkPolyData.h>
#include <vtkProperty.h>
#include <vtkCamera.h>
#include <vtkRenderer.h>
#include <vtkActor.h>
#include <vtkDataSetMapper.h>
#include <vtkSTLReader.h>
#include <vtkOBJReader.h>
#include <vtkLight.h>
#include <vtkAxesActor.h>
#include <vtkTransform.h>
#include <vtkPlane.h>
#include <vtkClipDataSet.h>
#include <vtkShrinkFilter.h>
#include <vtkGenericOpenGLRenderWindow.h>
#include <vtkInteractorStyle.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkOrientationMarkerWidget.h>
#include <vtkAnnotatedCubeActor.h>
#include <vtkDiskSource.h>
#include <vtkFollower.h>
#include <vtkPolyDataMapper.h>
#include <vtkVectorText.h>
#include <vtkAppendPolyData.h>
#include <vtkTextActor3D.h>
#include <vtkTextProperty.h>
#include <vtkLineSource.h>

#include <filesystem>

// Qt 相关头文件
#include <QDebug>
#include <QFileInfo>

VTKModelStudio::VTKModelStudio(QWidget* parent)
    : QVTKOpenGLNativeWidget(parent),
      m_modelLoaded(false),
      m_shrinkFilterEnabled(false),
      m_clipFilterEnabled(false),
      m_mouseInteractionEnabled(true),
      m_attitudeMarkerVisible(false),
      m_renderPending(false),
      m_lightEnabled(false),
      m_currentYaw(0.0),
      m_currentPitch(0.0),
      m_currentRoll(0.0)
{
    setAttribute(Qt::WA_TranslucentBackground, true);

    // 渲染节流定时器
    m_renderTimer = new QTimer(this);
    m_renderTimer->setSingleShot(true);
    connect(m_renderTimer, &QTimer::timeout, this, &VTKModelStudio::onRenderTimeout);

    initializeVTK();
    setupInteractorStyle();

    setupAxes();
    setAxesWorldVisible(false);  // 默认不显示坐标轴
    setupCompass();
    setupAttitudeMarker();  // 姿态指示器
    setupLighting();
    setLightEnabled(true);
    setMouseInteractionEnabled(false);  // 默认不启用鼠标交互
}

VTKModelStudio::~VTKModelStudio()
{
    clearModel();
    delete compass;  // 清理罗盘对象
}

void VTKModelStudio::initializeVTK()
{
    // 创建渲染窗口和渲染器
    m_renderWindow = vtkSmartPointer<vtkGenericOpenGLRenderWindow>::New();
    m_renderer = vtkSmartPointer<vtkRenderer>::New();

    // 设置背景
    m_renderer->GradientBackgroundOn();
    m_renderer->SetBackground(0.1, 0.2, 0.4);
    m_renderer->SetBackground2(0.0, 0.6, 0.5);

    this->setRenderWindow(m_renderWindow);
    m_renderWindow->AddRenderer(m_renderer);

    // 设置相机初始位置
    resetCamera();
}

void VTKModelStudio::setupInteractorStyle()
{
    // 获取交互器
    vtkRenderWindowInteractor* interactor = m_renderWindow->GetInteractor();
    if (!interactor)
    {
        return;
    }

    // 创建默认的交互器风格（支持鼠标拖动）
    m_interactorStyle = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
    interactor->SetInteractorStyle(m_interactorStyle);
}

vtkRenderer* VTKModelStudio::getRenderer()
{
    return m_renderer.Get();
}
vtkRenderWindow* VTKModelStudio::getRenderWindow()
{
    return m_renderWindow.Get();
}

void VTKModelStudio::setupLighting()
{
    m_light = vtkSmartPointer<vtkLight>::New();
    m_light->SetLightTypeToCameraLight();  // 设置为相机灯光
    m_light->SetIntensity(0.5);            // 总体强度系数

    // 设置默认光源位置和焦点
    m_light->SetPosition(0, 0, 3);          // 默认在Z轴正方向
    m_light->SetFocalPoint(0.0, 0.0, 0.0);  // 默认看向原点

    m_light->SetColor(1.0, 1.0, 1.0);  // 白光
    m_light->SetPositional(false);     // 方向光而非点光源
    setLightEnabled(true);
}

void VTKModelStudio::setupAxes()
{
    // 世界坐标系 姿态坐标轴
    m_axesWorldTransform = vtkSmartPointer<vtkTransform>::New();
    m_axesWorldTransform->Translate(0.0, 0.0, 0.0);

    m_axesWorld = vtkSmartPointer<vtkAxesActor>::New();
    m_axesWorld->SetUserTransform(m_axesWorldTransform);
    m_axesWorld->SetShaftTypeToCylinder();  // 轴类型：圆柱

    updateAxesScale();  // 初始设置，后续会根据模型尺寸动态调整

    // 设置标签
    m_axesWorld->SetAxisLabels(0);  // 启用标签显示, 1 = 显示标签，0 = 隐藏标签
    m_axesWorld->SetXAxisLabelText("X");
    m_axesWorld->SetYAxisLabelText("Y");
    m_axesWorld->SetZAxisLabelText("Z");

    // 模型坐标系 姿态坐标轴
    m_modelTransform = vtkSmartPointer<vtkTransform>::New();
    m_modelTransform->Identity();
    m_attitudeTransform = vtkSmartPointer<vtkTransform>::New();
    m_attitudeTransform->Identity();
}

void VTKModelStudio::updateAxesScale()
{
    if (!m_axesWorld)
    {
        return;
    }
    // 如果模型已加载，根据模型尺寸调整坐标轴大小
    if (m_modelLoaded)
    {
        double maxDimension = std::max({m_lengthX, m_lengthY, m_lengthZ});
        if (maxDimension > 0)
        {
            // 坐标轴长度设为模型最大尺寸的1.2倍，确保完全包围模型
            double axisLength = maxDimension * 1.2;
            m_axesWorld->SetTotalLength(axisLength, axisLength, axisLength);
            double baseRadius = maxDimension * 0.01;  // 基础半径
            m_axesWorld->SetCylinderRadius(std::min(baseRadius, 0.01));
            m_axesWorld->SetConeRadius(std::min(baseRadius * 10.0, 0.1));

            //// 设置坐标轴位置到模型中心
            // m_axesWorldTransform->Identity();
            // m_axesWorldTransform->Translate(m_centerX, m_centerY, m_centerZ);
        }
    }
    else
    {
        // 没有模型时的默认设置
        m_axesWorld->SetTotalLength(1.0, 1.0, 1.0);
        m_axesWorld->SetCylinderRadius(0.01);
        m_axesWorld->SetConeRadius(0.1);
    }
}

void VTKModelStudio::setupAttitudeMarker()
{
    // 创建坐标轴姿态指示器
    m_attitudeAxes = vtkSmartPointer<vtkAxesActor>::New();
    // m_attitudeAxes->SetShaftTypeToLine();
    // m_attitudeAxes->SetTotalLength(1.0, 1.0, 1.0);
    // m_attitudeAxes->SetNormalizedTipLength(0.2, 0.2, 0.2);
    // m_attitudeAxes->SetNormalizedShaftLength(0.8, 0.8, 0.8);
    // 设置轴标签
    m_attitudeAxes->SetXAxisLabelText("X");
    m_attitudeAxes->SetYAxisLabelText("Y");
    m_attitudeAxes->SetZAxisLabelText("Z");
    m_attitudeAxes->AxisLabelsOn();

    // 设置坐标轴使用模型变换
    m_attitudeAxes->SetUserTransform(m_attitudeTransform);

    // 创建方向标记小部件
    m_attitudeMarker = vtkSmartPointer<vtkOrientationMarkerWidget>::New();
    m_attitudeMarker->SetOutlineColor(0.9300, 0.5700, 0.1300);
    m_attitudeMarker->SetOrientationMarker(m_attitudeAxes);  // 默认使用坐标轴
    m_attitudeMarker->SetInteractor(m_renderWindow->GetInteractor());
    // m_attitudeMarker->SetViewport(0.0, 0.0, 0.2, 0.2);  // 左下角，大小20%
    m_attitudeMarker->SetViewport(0.7, 0.7, 1.0, 1.0);  // 右上角, 大小15%
    m_attitudeMarker->SetEnabled(true);
    m_attitudeMarker->InteractiveOff();  // 不允许拖拽指示器的位置
    m_attitudeMarker->SetEnabled(m_attitudeMarkerVisible);
}

void VTKModelStudio::setAttitudeMarkerVisible(bool visible)
{
    // 只有在模型加载后才能显示方向指示器
    if (!m_modelLoaded && visible)
    {
        qDebug() << "Cannot show attitude marker: no model loaded";
        return;
    }

    if (m_attitudeMarkerVisible == visible)
    {
        return;
    }

    m_attitudeMarkerVisible = visible;

    if (m_attitudeMarker)
    {
        m_attitudeMarker->SetEnabled(visible);
    }

    render();
}

void VTKModelStudio::setAttitudeMarkerViewport(double x, double y, double width, double height)
{
    if (!m_attitudeMarker)
    {
        return;
    }

    m_attitudeMarker->SetViewport(x, y, x + width, y + height);

    if (m_attitudeMarkerVisible)
    {
        render();
    }
}

void VTKModelStudio::setAttitudeMarkerInteractive(bool interactive)
{
    if (!m_attitudeMarker)
    {
        return;
    }

    if (interactive)
    {
        m_attitudeMarker->InteractiveOn();
    }
    else
    {
        m_attitudeMarker->InteractiveOff();
    }
}

void VTKModelStudio::setMouseInteractionEnabled(bool enabled)
{
    if (m_mouseInteractionEnabled == enabled)
    {
        return;
    }

    m_mouseInteractionEnabled = enabled;

    vtkRenderWindowInteractor* interactor = m_renderWindow->GetInteractor();
    if (!interactor)
    {
        return;
    }

    if (enabled)
    {
        // 启用鼠标交互 - 使用默认的TrackballCamera风格
        m_interactorStyle = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
    }
    else
    {
        // 禁用鼠标交互 - 使用无操作的交互器风格
        m_interactorStyle = vtkSmartPointer<vtkInteractorStyle>::New();
    }

    interactor->SetInteractorStyle(m_interactorStyle);
    render();
}

bool VTKModelStudio::loadModel(const std::string& file)
{
    if (file.empty())
    {
        qWarning() << "File path is empty";
        return false;
    }

    std::filesystem::path filePath(file);
    if (!std::filesystem::exists(filePath))
    {
        qWarning() << "File does not exist: " << QString::fromStdString(file);
        return false;
    }

    if (std::filesystem::file_size(filePath) == 0)
    {
        qWarning() << "File is empty: " << QString::fromStdString(file);
        return false;
    }
    std::string suffix = filePath.extension().string();
    // 移除扩展名中的点号，并转换为小写
    if (!suffix.empty() && suffix[0] == '.')
    {
        suffix = suffix.substr(1);
    }
    // 转换为小写
    std::transform(suffix.begin(), suffix.end(), suffix.begin(), ::tolower);
    if (suffix == "stl")
    {
        return loadStl(file);
    }
    else if (suffix == "obj")
    {
        return loadObj(file);
    }
    else
    {
        qWarning() << "Unsupported file format: " << QString::fromStdString(suffix);
        return false;
    }
}

bool VTKModelStudio::loadStl(const std::string& file)
{
    QString filePath = QString::fromStdString(file);
    qDebug() << "Loading STL file: " << filePath;

    // 清除现有模型
    clearModel();

    // 创建STL读取器
    m_stlReader = vtkSmartPointer<vtkSTLReader>::New();
    m_stlReader->SetFileName(filePath.toUtf8().constData());

    try
    {
        m_stlReader->Update();
    }
    catch (...)
    {
        qWarning() << "Failed to read STL file: " << filePath;
        return false;
    }

    // 检查数据有效性
    if (m_stlReader->GetOutput()->GetNumberOfPoints() == 0)
    {
        qWarning() << "STL file contains no data: " << filePath;
        return false;
    }

    // 调整actors和mappers大小
    m_mappers.resize(1);
    m_actors.resize(1);

    // 创建映射器和演员
    m_mappers[0] = vtkSmartPointer<vtkDataSetMapper>::New();
    m_mappers[0]->SetInputConnection(m_stlReader->GetOutputPort());

    m_actors[0] = vtkSmartPointer<vtkActor>::New();
    m_actors[0]->SetMapper(m_mappers[0]);

    // 设置默认颜色和属性
    vtkSmartPointer<vtkNamedColors> colors = vtkSmartPointer<vtkNamedColors>::New();
    QColor color("#A93226");
    m_actors[0]->GetProperty()->SetColor(color.redF(), color.greenF(), color.blueF());
    m_actors[0]->GetProperty()->SetSpecular(0.5);
    m_actors[0]->GetProperty()->SetSpecularPower(5);

    // 性能优化：对于大型STL文件使用平坦着色
    vtkSmartPointer<vtkPolyData> stlPolyData = m_stlReader->GetOutput();
    if (stlPolyData->GetNumberOfPolys() > 10000)
    {
        m_actors[0]->GetProperty()->SetInterpolationToFlat();
    }

    // 添加到渲染器
    m_renderer->AddActor(m_actors[0]);

    m_modelLoaded = true;
    m_currentModelPath = filePath;

    // 重置模型变换
    m_modelTransform->Identity();
    m_currentYaw = 0.0;
    m_currentPitch = 0.0;
    m_currentRoll = 0.0;

    if (m_attitudeTransform)
    {
        m_attitudeTransform->Identity();
    }

    // 更新状态
    m_modelLoaded = true;
    m_currentModelPath = filePath;

    // 重置相机并渲染
    resetCamera();
    render();

    getModelStatistics();  // 统计信息
    updateAxesScale();     // 更新坐标轴尺寸

    return true;
}

bool VTKModelStudio::loadObj(const std::string& file)
{
    QString filePath = QString::fromStdString(file);
    qDebug() << "Loading OBJ file: " << filePath;

    // 清除现有模型
    clearModel();

    // 创建OBJ读取器
    m_objReader = vtkSmartPointer<vtkOBJReader>::New();
    m_objReader->SetFileName(filePath.toUtf8().constData());

    try
    {
        m_objReader->Update();
    }
    catch (...)
    {
        qWarning() << "Failed to read OBJ file: " << filePath;
        return false;
    }

    // 检查数据有效性
    if (m_objReader->GetOutput()->GetNumberOfPoints() == 0)
    {
        qWarning() << "OBJ file contains no data: " << filePath;
        return false;
    }

    // 调整actors和mappers大小
    m_mappers.resize(1);
    m_actors.resize(1);

    // 创建映射器和演员
    m_mappers[0] = vtkSmartPointer<vtkDataSetMapper>::New();
    m_mappers[0]->SetInputConnection(m_objReader->GetOutputPort());

    m_actors[0] = vtkSmartPointer<vtkActor>::New();
    m_actors[0]->SetMapper(m_mappers[0]);

    // 对于OBJ文件，不设置默认颜色，保持原有的材质和纹理
    // 只设置一些通用的渲染属性
    m_actors[0]->GetProperty()->SetSpecular(0.3);      // 降低高光强度
    m_actors[0]->GetProperty()->SetSpecularPower(20);  // 设置高光指数

    // 性能优化：对于大型OBJ文件使用平坦着色
    vtkSmartPointer<vtkPolyData> objPolyData = m_objReader->GetOutput();
    if (objPolyData->GetNumberOfPolys() > 10000)
    {
        m_actors[0]->GetProperty()->SetInterpolationToFlat();
    }
    else
    {
        // 对于小型模型，使用平滑着色以获得更好的视觉效果
        m_actors[0]->GetProperty()->SetInterpolationToGouraud();
    }

    // 添加到渲染器
    m_renderer->AddActor(m_actors[0]);

    m_modelLoaded = true;
    m_currentModelPath = filePath;

    // 重置模型变换
    m_modelTransform->Identity();
    m_currentYaw = 0.0;
    m_currentPitch = 0.0;
    m_currentRoll = 0.0;

    if (m_attitudeTransform)
    {
        m_attitudeTransform->Identity();
    }

    // 重置相机并渲染
    resetCamera();
    render();

    getModelStatistics();  // 统计信息
    updateAxesScale();     // 更新坐标轴尺寸

    return true;
}

void VTKModelStudio::clearModel()
{
    if (!m_modelLoaded)
    {
        return;
    }

    // 从渲染器中移除所有actors
    for (auto& actor : m_actors)
    {
        if (actor)
        {
            m_renderer->RemoveActor(actor);
        }
    }
    // 重置变换状态
    if (m_modelTransform)
    {
        m_modelTransform->Identity();
    }
    m_currentYaw = 0.0;
    m_currentPitch = 0.0;
    m_currentRoll = 0.0;

    // 重置姿态指示器
    if (m_attitudeMarkerVisible && m_attitudeMarker)
    {
        m_attitudeMarker->SetEnabled(false);
        m_attitudeMarkerVisible = false;
    }
    if (m_attitudeTransform)
    {
        m_attitudeTransform->Identity();
    }

    // 清空向量
    m_actors.clear();
    m_mappers.clear();

    // 移除坐标轴
    if (m_axesWorld)
    {
        m_renderer->RemoveActor(m_axesWorld);
    }
    // 重置过滤器
    m_shrinkFilterEnabled = false;
    m_clipFilterEnabled = false;

    // 重置读取器
    m_stlReader = nullptr;
    m_objReader = nullptr;

    // 更新状态
    m_currentModelPath.clear();
    m_modelLoaded = false;

    render();
}

void VTKModelStudio::resetCamera()
{
    if (!m_renderer)
    {
        return;
    }
    m_renderer->GetActiveCamera()->SetFocalPoint(0, 0, 0);  // 相机看向的点（世界坐标）
    m_renderer->GetActiveCamera()->SetPosition(0, 0, 1);    // 相机在世界坐标系中的位置
    m_renderer->GetActiveCamera()->SetViewUp(1, 0, 0);      // 定义相机的"上"方向
    m_renderer->ResetCamera();
    render();
}

void VTKModelStudio::setCameraFocalPoint(double x, double y, double z)
{
    if (!m_renderer)
    {
        return;
    }
    m_renderer->GetActiveCamera()->SetFocalPoint(x, y, z);
    m_renderer->ResetCamera();
    render();
}

void VTKModelStudio::setCameraPosition(double x, double y, double z)
{
    if (!m_renderer)
    {
        return;
    }
    m_renderer->GetActiveCamera()->SetPosition(x, y, z);
    m_renderer->ResetCamera();
    render();
}

void VTKModelStudio::setCameraViewUp(double x, double y, double z)
{
    if (!m_renderer)
    {
        return;
    }
    m_renderer->GetActiveCamera()->SetViewUp(x, y, z);
    m_renderer->ResetCamera();
    render();
}

void VTKModelStudio::zoomCamera(double factor)
{
    if (!m_renderer)
    {
        return;
    }

    vtkCamera* camera = m_renderer->GetActiveCamera();
    if (camera)
    {
        camera->Zoom(factor);
        render();
    }
}

void VTKModelStudio::setModelRotation(double yaw, double pitch, double roll)
{
    if (!m_modelLoaded || m_actors.empty())
    {
        return;
    }

    // 更新当前角度
    m_currentYaw = yaw;
    m_currentPitch = pitch;
    m_currentRoll = roll;

    // 重置变换
    m_modelTransform->Identity();

    // 将模型移动到原点（基于模型中心）
    if (m_modelLoaded)
    {
        m_modelTransform->Translate(-m_centerX, -m_centerY, -m_centerZ);
    }

    // 标准航空航天顺序：航向 -> 横滚 -> 俯仰
    m_modelTransform->RotateZ(yaw);    // 航向 (绕Z轴)
    m_modelTransform->RotateX(roll);   // 横滚 (绕X轴)
    m_modelTransform->RotateY(pitch);  // 俯仰 (绕Y轴)

    // 将模型移回原位置
    if (m_modelLoaded)
    {
        m_modelTransform->Translate(m_centerX, m_centerY, m_centerZ);
    }

    // 应用变换到所有actor
    for (auto& actor : m_actors)
    {
        if (actor)
        {
            actor->SetUserTransform(m_modelTransform);
        }
    }

    // 姿态指示器
    if (m_attitudeMarkerVisible)
    {
        m_attitudeTransform->Identity();
        m_attitudeTransform->RotateZ(yaw);    // 航向
        m_attitudeTransform->RotateX(roll);   // 横滚
        m_attitudeTransform->RotateY(pitch);  // 俯仰
    }
    requestRender();
}

void VTKModelStudio::setYaw(double angle)
{
    setModelRotation(angle, m_currentPitch, m_currentRoll);
}

void VTKModelStudio::setPitch(double angle)
{
    setModelRotation(m_currentYaw, angle, m_currentRoll);
}

void VTKModelStudio::setRoll(double angle)
{
    setModelRotation(m_currentYaw, m_currentPitch, angle);
}

void VTKModelStudio::setModelColor(double r, double g, double b)
{
    for (auto& actor : m_actors)
    {
        if (actor)
        {
            actor->GetProperty()->SetColor(r, g, b);
        }
    }
    render();
}

void VTKModelStudio::setModelColor(const QColor& color)
{
    setModelColor(color.redF(), color.greenF(), color.blueF());
}

void VTKModelStudio::setModelOpacity(double opacity)
{
    for (auto& actor : m_actors)
    {
        if (actor)
        {
            actor->GetProperty()->SetOpacity(opacity);
        }
    }
    render();
}

void VTKModelStudio::setModelRepresentation(int representation)
{
    for (auto& actor : m_actors)
    {
        if (actor)
        {
            switch (representation)
            {
                case 0:  // Points
                    actor->GetProperty()->SetRepresentationToPoints();
                    break;
                case 1:  // Wireframe
                    actor->GetProperty()->SetRepresentationToWireframe();
                    break;
                case 2:  // Surface
                default:
                    actor->GetProperty()->SetRepresentationToSurface();
                    break;
            }
        }
    }
    render();
}

void VTKModelStudio::setBackgroundColor(double r, double g, double b)
{
    if (!m_renderer)
    {
        return;
    }
    m_renderer->SetBackground(r, g, b);
    render();
}

void VTKModelStudio::setBackgroundColor(const QColor& color)
{
    setBackgroundColor(color.redF(), color.greenF(), color.blueF());
}

void VTKModelStudio::setGradientBackground(bool enabled)
{
    if (!m_renderer)
    {
        return;
    }

    if (enabled)
    {
        m_renderer->GradientBackgroundOn();
    }
    else
    {
        m_renderer->GradientBackgroundOff();
    }
    render();
}

void VTKModelStudio::setBackgroundGradient(double r1, double g1, double b1, double r2, double g2, double b2)
{
    if (!m_renderer)
    {
        return;
    }

    m_renderer->GradientBackgroundOn();
    m_renderer->SetBackground(r1, g1, b1);
    m_renderer->SetBackground2(r2, g2, b2);
    render();
}

void VTKModelStudio::setLightEnabled(bool enabled)
{
    if (!m_renderer)
    {
        return;
    }

    // 移除直接返回的逻辑，确保每次调用都执行
    m_lightEnabled = enabled;
    if (m_lightEnabled)
    {
        // 确保光源已创建
        if (!m_light)
        {
            setupLighting();  // 重新创建光源
        }
        m_renderer->AddLight(m_light);
    }
    else
    {
        if (m_light)
        {
            m_renderer->RemoveLight(m_light);
        }
    }

    // 强制渲染更新
    render();
}

void VTKModelStudio::setLightIntensity(double intensity)
{
    if (m_light)
    {
        m_light->SetIntensity(intensity);
        render();
    }
}

void VTKModelStudio::setLightPosition(double x, double y, double z)
{
    if (m_light)
    {
        m_light->SetPosition(x, y, z);
        render();
    }
}

void VTKModelStudio::setLightFocalPoint(double x, double y, double z)
{
    if (m_light)
    {
        m_light->SetFocalPoint(x, y, z);
        render();
    }
}

void VTKModelStudio::getLightPosition(double& x, double& y, double& z)
{
    if (m_light)
    {
        double* pos = m_light->GetPosition();
        x = pos[0];
        y = pos[1];
        z = pos[2];
    }
    else
    {
        x = y = z = 0.0;
    }
}

void VTKModelStudio::getLightFocalPoint(double& x, double& y, double& z)
{
    if (m_light)
    {
        double* focal = m_light->GetFocalPoint();
        x = focal[0];
        y = focal[1];
        z = focal[2];
    }
    else
    {
        x = y = z = 0.0;
    }
}

void VTKModelStudio::setAxesWorldVisible(bool visible)
{
    if (!m_renderer)
    {
        return;
    }

    if (visible)
    {
        m_renderer->AddActor(m_axesWorld);
    }
    else
    {
        m_renderer->RemoveActor(m_axesWorld);
    }
    render();
}

void VTKModelStudio::setAxesWorldPosition(double x, double y, double z)
{
    if (m_axesWorldTransform)
    {
        m_axesWorldTransform->Identity();
        m_axesWorldTransform->Translate(x, y, z);
        render();
    }
}

void VTKModelStudio::setShrinkFilterEnabled(bool enabled, double factor)
{
    if (!m_modelLoaded || (!m_stlReader && !m_objReader))
    {
        return;
    }

    m_shrinkFilterEnabled = enabled;

    if (enabled)
    {
        applyShrinkFilter();
    }
    else
    {
        // 禁用收缩过滤器，恢复原始连接
        if (m_mappers.size() > 0 && m_mappers[0])
        {
            if (m_stlReader)
            {
                m_mappers[0]->SetInputConnection(m_stlReader->GetOutputPort());
            }
            else if (m_objReader)
            {
                m_mappers[0]->SetInputConnection(m_objReader->GetOutputPort());
            }
        }
    }
    render();
}

void VTKModelStudio::setClipFilterEnabled(bool enabled)
{
    if (!m_modelLoaded || (!m_stlReader && !m_objReader))
    {
        return;
    }

    m_clipFilterEnabled = enabled;

    if (enabled)
    {
        applyClipFilter();
    }
    else
    {
        // 禁用裁剪过滤器，恢复原始连接
        if (m_mappers.size() > 0 && m_mappers[0])
        {
            if (m_stlReader)
            {
                m_mappers[0]->SetInputConnection(m_stlReader->GetOutputPort());
            }
            else if (m_objReader)
            {
                m_mappers[0]->SetInputConnection(m_objReader->GetOutputPort());
            }
        }
    }
    render();
}

void VTKModelStudio::setClipPlane(double originX, double originY, double originZ, double normalX, double normalY, double normalZ)
{
    if (!m_clipPlane)
    {
        return;
    }

    m_clipPlane->SetOrigin(originX, originY, originZ);
    m_clipPlane->SetNormal(normalX, normalY, normalZ);

    if (m_clipFilterEnabled)
    {
        render();
    }
}

void VTKModelStudio::render()
{
    if (m_renderWindow)
    {
        m_renderWindow->Render();
    }
}

void VTKModelStudio::requestRender()
{
    if (!m_renderPending)
    {
        // 最快100毫秒渲染一次
        m_renderPending = true;
        m_renderTimer->start(16);  // 16毫秒 = 60fps限制
    }
}

void VTKModelStudio::onRenderTimeout()
{
    if (m_renderPending)
    {
        render();
        m_renderPending = false;
    }
}

void VTKModelStudio::getModelStatistics()
{
    vtkSmartPointer<vtkPolyData> polyData;

    if (m_stlReader)
    {
        polyData = m_stlReader->GetOutput();
    }
    else if (m_objReader)
    {
        polyData = m_objReader->GetOutput();
    }
    else
    {
        return;
    }

    if (!polyData)
    {
        return;
    }

    vtkSmartPointer<vtkTriangleFilter> triangleFilter = vtkSmartPointer<vtkTriangleFilter>::New();
    vtkSmartPointer<vtkMassProperties> massProperty = vtkSmartPointer<vtkMassProperties>::New();

    triangleFilter->SetInputData(polyData);
    triangleFilter->Update();

    // 1. 几何边界和尺寸信息
    double bounds[6];
    polyData->GetBounds(bounds);
    m_lengthX = m_lengthY = m_lengthZ = 0.0;
    m_lengthX = bounds[1] - bounds[0];  // X方向尺寸
    m_lengthY = bounds[3] - bounds[2];  // Y方向尺寸
    m_lengthZ = bounds[5] - bounds[4];  // Z方向尺寸

    // 模型中心点坐标
    m_centerX = m_centerY = m_centerZ = 0.0;
    m_centerX = (bounds[0] + bounds[1]) / 2.0;
    m_centerY = (bounds[2] + bounds[3]) / 2.0;
    m_centerZ = (bounds[4] + bounds[5]) / 2.0;

    // 基础统计信息
    m_cells = polyData->GetNumberOfPolys();
    m_points = polyData->GetNumberOfPoints();

    QString boundsString = QString("X:[%1, %2]  Y:[%3, %4]  Z:[%5, %6]").arg(bounds[0], 0, 'f', 3).arg(bounds[1], 0, 'f', 3).arg(bounds[2], 0, 'f', 3).arg(bounds[3], 0, 'f', 3).arg(bounds[4], 0, 'f', 3).arg(bounds[5], 0, 'f', 3);

    // 调试输出所有统计信息
    qDebug() << "File:" << m_currentModelPath;
    qDebug() << "   Size X: " << m_lengthX;
    qDebug() << "   Size Y: " << m_lengthY;
    qDebug() << "   Size Z: " << m_lengthZ;
    qDebug() << "   Center: (" << m_centerX << "," << m_centerY << "," << m_centerZ << ")";
    qDebug() << "   Bounds: " << boundsString;
    qDebug() << "   Points: " << m_points;
    qDebug() << "   Cells: " << m_cells;
}

void VTKModelStudio::applyShrinkFilter()
{
    if (!m_shrinkFilterEnabled || m_mappers.empty())
    {
        return;
    }

    m_shrinkFilter = vtkSmartPointer<vtkShrinkFilter>::New();

    if (m_stlReader)
    {
        m_shrinkFilter->SetInputConnection(m_stlReader->GetOutputPort());
    }
    else if (m_objReader)
    {
        m_shrinkFilter->SetInputConnection(m_objReader->GetOutputPort());
    }
    else
    {
        return;
    }

    m_shrinkFilter->SetShrinkFactor(0.5);
    m_shrinkFilter->Update();

    m_mappers[0]->SetInputConnection(m_shrinkFilter->GetOutputPort());
}

void VTKModelStudio::applyClipFilter()
{
    if (!m_clipFilterEnabled || m_mappers.empty())
    {
        return;
    }

    m_clipFilter = vtkSmartPointer<vtkClipDataSet>::New();
    m_clipPlane = vtkSmartPointer<vtkPlane>::New();

    if (m_stlReader)
    {
        m_clipFilter->SetInputConnection(m_stlReader->GetOutputPort());
    }
    else if (m_objReader)
    {
        m_clipFilter->SetInputConnection(m_objReader->GetOutputPort());
    }
    else
    {
        return;
    }

    m_clipPlane->SetOrigin(0.0, 0.0, 0.0);
    m_clipPlane->SetNormal(-1.0, 0.0, 0.0);
    m_clipFilter->SetClipFunction(m_clipPlane);

    m_mappers[0]->SetInputConnection(m_clipFilter->GetOutputPort());
}

QColor VTKModelStudio::getBackgroundColor() const
{
    if (!m_renderer)
    {
        return QColor();
    }

    double* bg = m_renderer->GetBackground();
    if (!bg)
    {
        return QColor();
    }

    return QColor(static_cast<int>(bg[0] * 255), static_cast<int>(bg[1] * 255), static_cast<int>(bg[2] * 255));
}

QColor VTKModelStudio::getBackgroundColor2() const
{
    if (!m_renderer)
    {
        return QColor();
    }

    double* bg2 = m_renderer->GetBackground2();
    if (!bg2)
    {
        return QColor();
    }

    return QColor(static_cast<int>(bg2[0] * 255), static_cast<int>(bg2[1] * 255), static_cast<int>(bg2[2] * 255));
}

void VTKModelStudio::setupCompass()
{
    compass = new VTKCompassStudio(this);
    compass->setRenderer(m_renderer);
    // 默认不显示罗盘
    compass->setVisible(false);
}